#!/bin/bash
killall daemon
killall tuntap_bb
DEVICE_ID="1d6b:8030"
TARGET_IP="192.168.144.55"
INIT_DONE=0  # 0 表示未初始化，1 表示已初始化

while true; do
    if lsusb | grep -q "$DEVICE_ID"; then
        if [ "$INIT_DONE" -eq 0 ]; then
            INIT_DONE=1  # 标记已初始化
            echo "Device $DEVICE_ID detected, initializing 401"

            ln -s /dev/net/tun /dev/tun 2>/dev/null
            echo "Initializing Linux TUN"
            sleep 1

            ./bin/daemon &
            echo "Starting daemon"
            sleep 8

            #./dev_helper/tuntap_bb -p 2 -i 192.168.144.66 -u 0 -d tun -r 40000 -t 60000 &
            ./dev_helper/tuntap_bb -p 2 -i 192.168.144.66 -u 0 -d tun -r 80000 -t 20000 &
            sleep 8

            echo "Success, attempting to ping $TARGET_IP"

            if ping -c 1 -W 1 $TARGET_IP &> /dev/null; then
                echo "Success: $TARGET_IP is reachable"
            else
                echo "Failed: $TARGET_IP is unreachable"
            fi

            
        fi
    else
        if [ "$INIT_DONE" -eq 1 ]; then
            echo "Device $DEVICE_ID not detected, stopping services..."
            killall daemon
            killall tuntap_bb
            INIT_DONE=0  # 设备丢失，重置状态
        fi
    fi

    sleep 1
done
